package com.fmdj.nebula.task;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.map.MapUtil;
import com.fmdj.common.exception.GlobalException;
import com.fmdj.nebula.db.dao.OrderMonitoringDao;
import com.fmdj.nebula.db.dao.OrderVoiceTextDao;
import com.fmdj.nebula.db.pojo.OrderMonitoringEntity;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.model.ciModel.auditing.AuditingJobsDetail;
import com.qcloud.cos.model.ciModel.auditing.SectionInfo;
import com.qcloud.cos.model.ciModel.auditing.TextAuditingRequest;
import com.qcloud.cos.model.ciModel.auditing.TextAuditingResponse;
import com.qcloud.cos.region.Region;
import feign.Client;
import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.util.hash.Hash;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Component
public class VoiceTextCheckTask {

    @Value("${tencent.cloud.secretId}")
    private String secretId;

    @Value("${tencent.cloud.secretKey}")
    private String secretKey;

    @Value("${tencent.cloud.region-public}")
    private String regionPublic;

    @Value("${tencent.cloud.bucket-public}")
    private String bucketPublic;

    @Autowired
    private OrderMonitoringDao  orderMonitoringDao;

    @Autowired
    private OrderVoiceTextDao orderVoiceTextDao;

    @Async
    @Transactional
    public void checkText(long orderId,String content,String uuid) {
        //默认审核结果为normal
        String label = "normal";
        //默认人工建议为Pass
        String suggestion = "Pass";

        //建议建议映射模板
        HashMap<String, String> template = new HashMap<>() {
            {
                put("0", "Pass");
                put("1", "Block");
                put("2", "Review");
            }
        };
        //如果文本内容不为空，进行审核流程
        if (StringUtil.isNotBlank(content)) {

            //获取一个数据万象的Client连接
            BasicCOSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            Region region = new Region(regionPublic);
            ClientConfig config = new ClientConfig(region);
            COSClient client = new COSClient(cred, config);

            //创建任务请求对象
            TextAuditingRequest request = new TextAuditingRequest();
            //添加请求参数
            request.setBucketName(bucketPublic);
            //设置审查,文本内容的Base64编码
            request.getInput().setContent(Base64.encode(content));
            ///设置检测类型为 "all"，表示检测所有可能的违规内容
            request.getConf().setDetectType("all");
            //发起文本审核请求，并获取响应结果
            TextAuditingResponse response = client.createAuditingTextJobs(request);

            AuditingJobsDetail detail = response.getJobsDetail();
            String state = detail.getState();

            //存储每个审核片段中命中的关键词
            ArrayList keyWords = new ArrayList<>();

            //审核成功,则处理审核结果
            if ("Success".equals(state)) {
                label = detail.getLabel();//获取审核结果标签
                String result = detail.getResult();//根据审核结果选择相应的建议 (0（审核正常），1 （判定为违规敏感文件），2（疑似敏感，建议人工复核）)
                suggestion = template.get(result);

                // 处理每个审核片段中的关键词
                List<SectionInfo> sectionList = detail.getSectionList();
                for (SectionInfo info : sectionList) {
                    String keywords_1 = info.getPornInfo().getKeywords();
                    String keywords_2 = info.getAbuseInfo().getKeywords();
                    String keywords_3 = info.getIllegalInfo().getKeywords();

                    if (keywords_1.length() > 0) {
                        List<String> list = Arrays.asList(keywords_1.split(","));
                        keyWords.addAll(list);
                    }
                    if (keywords_2.length() > 0) {
                        List<String> list = Arrays.asList(keywords_2.split(","));
                        keyWords.addAll(list);
                    }
                    if (keywords_3.length() > 0) {
                        List<String> list = Arrays.asList(keywords_3.split(","));
                        keyWords.addAll(list);
                    }
                }

                //根据 UUID 查询代驾语音文本记录的 ID
                Long id = orderVoiceTextDao.searchIdByUuid(uuid);
                if (id == null) {
                    throw new GlobalException("没有找到代驾语音文本记录");
                }

                // 更新审核结果到数据库fmdj.order_voice_text
                HashMap map = new HashMap<>();
                map.put("id", id);
                map.put("keyWords", keyWords);
                map.put("label", label);
                map.put("suggestion", suggestion);

                int rows = orderVoiceTextDao.updateCheckResult(map);
                if (rows != 1) {
                    throw new GlobalException("更新内容检查结果失败");
                }

                //查询订单原有的录音文本数量和需要人工审核的文本数量
                HashMap hashMap = orderMonitoringDao.searchOrderRecordsAndReviews(orderId);
                id = MapUtil.getLong(hashMap, "id");
                Integer records = MapUtil.getInt(hashMap, "records");
                Integer reviews = MapUtil.getInt(hashMap, "reviews");

                // 更新订单的监控信息
                OrderMonitoringEntity entity = new OrderMonitoringEntity();
                entity.setId(id);
                entity.setOrderId(orderId);
                entity.setRecords(records + 1);//每审核一段文本,相当于审核了对应的录音,records自增
                if (suggestion.equals("Review")) {
                    entity.setReviews(reviews + 1);//需要人工审核的文本自增
                }
                if (suggestion.equals("Block")) {
                    entity.setSafety("dangerous");//出现违规内容,提升安全等级为danger
                }
                rows = orderMonitoringDao.updateOrderMonitoring(entity);

                if (rows != 1) {
                    throw new GlobalException("更新订单监控记录失败");
                }

            }
        }
    }
}
